package com.umfb.edu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.umfb.demo.service.edu.IFileUploadService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by zcah on 18-7-19.
 */
@Service
public class FileUploadServiceImpl implements IFileUploadService {

    @Value("${jt.qiniu.access_key}")
    private String uploadAccessKey;

    @Value("${jt.qiniu.secret_key}")
    private String uploadSecretKey;

    @Value("${jt.qiniu.bucket}")
    private String bucket;

    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);
    private String generateKey() {
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyMMddHHss");
        String current = format.format(now);
        StringBuilder sb = new StringBuilder(current);
        String rand = RandomStringUtils.random(4, "0123456789");
        Random random = new Random(now.getTime());
        int idx1 = random.nextInt(9);
        sb.insert(idx1, rand.substring(0, 2));
        int idx2 = random.nextInt(9);
        sb.insert(idx2, rand.substring(2));
        sb.insert(sb.length() - 2, rand.substring(1, 3));
        return sb.toString();
    }
    @Override
    public String imageUpload(byte[] fileb) throws Exception {
        String filename = generateKey();
        qiniu(filename,fileb);
        return filename;
    }

    private void qiniu(String key, byte[] b) {
        if (!StringUtils.isEmpty(key)) {

            try {
                Configuration config= new Configuration(Zone.zone0());
                Auth auth = Auth.create(this.uploadAccessKey, this.uploadSecretKey);
                String token = auth.uploadToken(bucket, key);
                UploadManager uploadManager = new UploadManager(config);
                uploadManager.put(b, key, token);

            } catch (QiniuException e) {
                e.printStackTrace();
                Response r = e.response;
                logger.error(e.toString());
                try {
                    logger.error(r.bodyString());
                } catch (QiniuException e1) {
                    // ignore
                }
            }
        }
    }

    @Override
    public String addWeixinUploadModel(String serverId) {
        return null;
    }

    @Override
    public String thirdFileUploadByUrl(String urlStr, String filepath, String fileName) throws Exception {
        return null;
    }
    
    
}
